from django.shortcuts import render,redirect
from django.contrib.auth.hashers import make_password, check_password
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse
from .. import models
import time,os
from shop.settings import BASE_DIR
from django.core.paginator import Paginator
from django.db.models import Q
from django.contrib.auth.decorators import permission_required
# Create your views here.

#会员列表页 
@permission_required('myadmin.create_User',raise_exception=True)
def vipuser(request):
    infos = models.Users.objects.all().exclude(status=3)
    
    #搜索功能
    #接受类型
    types = request.GET.get('type')
    #接受关键字
    search = request.GET.get('search')
    #判断是否搜索内容
    if types:
        if types=='all':
            infos = models.Users.objects.filter(Q(age__contains=search)|Q(username__contains=search)|Q(phone__contains=search)).exclude(status=3)
        #根据id username phone 查询
        elif types=='uname':
            infos = models.Users.objects.filter(username__contains=search).exclude(status=3)
        elif types == 'uage':
            infos = models.Users.objects.filter(age__contains=search)

        elif types=='uphone':
            infos = models.Users.objects.filter(phone__contains=search)
        

    #分页
    # 实例化分页对象
    p = Paginator(infos, 2)
    #一共可以分多少页
    sumpage=p.num_pages
    # 取第几页的数据
     # 接受用户的页码
    page = int(request.GET.get('p',1))
    # 第几页的数据
    page1 = p.page(page)

    # 判断 如果用输入的页码<=3 显示前五个页码
    if page<=3:
        # 页码的迭代序列  [1,2,3,4,5,6,7]
        prange = p.page_range[:5]
    elif page+2>=sumpage:
        prange = p.page_range[-5:]
    else:
        prange = p.page_range[page-3:page+2]


    return render(request,'myadmin/table-list.html',{'users':page1,'prange':prange,'page':page,'sumpage':sumpage})

#添加用户
@permission_required('myadmin.create_User',raise_exception=True)
def adduser(request):
    if request.method=="GET":
        return render(request,'myadmin/adduser.html')
    elif request.method=="POST":
        #接受用户数据
        userinfo = request.POST.dict()
        userinfo.pop('csrfmiddlewaretoken')

        myfile = request.FILES.get('head_url',None)
        #文件上传
        if not myfile:
            return HttpResponse("<script>alert('请选择头像');location.href=''</script>")
        userinfo['head_url']=upload(myfile)
        # 密码加密
        userinfo['password']=make_password(userinfo['password'], None, 'pbkdf2_sha256')
        # 错误处理
        try:
            #写入数据
            user = models.Users(**userinfo)
            user.save()
            return redirect(reverse('myadmin_vipuser'))
        except:
            return HttpResponse("<script>alert('添加失败！');location.href=''</script>")


#删除用户
@permission_required('myadmin.create_User',raise_exception=True)
def deluser(request):
    uid = request.GET.get('uid')
    user = models.Users.objects.get(id=uid)
    user.status = 3
    user.save()
    return redirect(reverse('myadmin_vipuser'))

#修改用户信息
@permission_required('myadmin.create_User',raise_exception=True)
def edituser(request):
    #接收用户id
    uid = request.GET.get('uid')
    #判断传输类型，如果是get 直接跳转到修页面
    if request.method=="GET":
        user = models.Users.objects.get(id=uid)
        return render(request,'myadmin/edit.html',{'user':user})
    #如果是post类型，则获取并更新数据
    elif request.method=='POST':
        #获取提交的数据并转化为字典
        userinfo = request.POST.dict()
        #获取当前的数据
        uinfo = models.Users.objects.get(id=uid)
        #更新数据
        uinfo.username = userinfo['username']
        uinfo.phone = userinfo['phone']
        uinfo.age = userinfo['age']
        uinfo.sex = userinfo['sex']
        #判断头像是否上传
        file = request.FILES.get('head_url')
        if file:
            #有头像上传，则删除旧头像
            #   注'.'为当前项目下（manage.py同级目录）
            os.remove('.'+uinfo.head_url)
            #将新的图片重命名后赋予headurl变量
            headurl = upload(file)
            #重新赋值
            uinfo.head_url=headurl
        uinfo.save()
        return HttpResponse("<script>alert('修改成功');location.href='/myadmin/vipuser/';</script>")

# 会员状态的更新
def user_set_status(request):
    # 通过uid获取当前会员对象
    ob = Users.objects.get(id=request.GET.get('uid'))
    ob.status = request.GET.get('status')
    ob.save()
    return JsonResponse({'msg':'状态更新成功','code':0})

#重置密码
def respwd(request):
#接收uid
    uid = request.GET.get('uid')
#获取当前数据
    user = models.Users.objects.get(id=uid)
#重新赋值并加密
    user.password = make_password('123456',None,'pbkdf2_sha256')
    user.save()
    data={'msg':'修改成功'}
    return JsonResponse(data)

#修改状态
def changes(request):
    #获取uid 获取状态值
    uid = request.GET.get('uid')
    status = request.GET.get('status')
    print(status)
    try:
        user = models.Users.objects.get(id=uid)
        user.status=int(status)
        user.save()
        msg={'msg':'修改成功'}
        return JsonResponse(msg)
    except:
        msg={'msg':'修改失败'}
        return JsonResponse(msg)


def upload(myfile):
    #重新命名上传的图片
    filename = str(time.time())+"."+myfile.name.split('.').pop()
    destination = open("./static/pics/"+filename,"wb+")
    for chunk in myfile.chunks():      # 分块写入文件  
        destination.write(chunk)  
    destination.close()
    # /static/pics/filename
    return '/static/pics/'+filename
